package seller

import (
	"dhfshop/models/seller"
	"dhfshop/models/sale"
	"time"
	"strconv"
	"dhfshop/utils/helper"
	"encoding/json"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type FareTempController struct {
	base.BaseController
}

func (this *FareTempController) List() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	var allowStoreId []int64
	if this.CurrentUser != nil {
	    allowStoreId = this.CurrentUser.AllowStoreId
	}
	//beego.Debug("allowStoreId:", allowStoreId)
	l, cnt, err := seller.GetAllFareTemplates(allowStoreId,query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	} else {
		r := struct {
		    TotalCount   int64     `json:"total_count"`
	        FareTemp    []*seller.FareTemplate `json:"fare_temp"`
	    }{TotalCount: cnt, FareTemp: l}
	    this.Data["json"] = r
	}
	this.ServeJSON()
}

func (this *FareTempController) Post() {
	var v seller.FareTemplate
	this.ParseForm(&v)
	valid := validation.Validation{}
	//valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if v.FareId == 0 {    //add template
		fareId, err := seller.AddFareTemplate(&v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		v.FareId = fareId
		if len(v.CarryModesJson) > 0 {
			err := json.Unmarshal([]byte(v.CarryModesJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, modes := range v.CarryModes {
				//modes.PartnerId = v.PartnerId
				modes.Fare = &v               // pay more attention
			}
			if err := seller.AddMultiModels(v.CarryModes); err != nil {
				this.ServeError(err.Error())
				return
			}	
	    }
	}else{                                 // add template carry_mode
		oldFareTemp, err := seller.GetFareTemplateById(v.FareId)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		if len(v.CarryModesJson) > 0 {
			err := json.Unmarshal([]byte(v.CarryModesJson), &v)
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			for _, modes := range v.CarryModes {
				//modes.PartnerId = oldFareTemp.PartnerId
				modes.Fare = oldFareTemp               // pay more attention
			}
			if err := seller.AddMultiModels(v.CarryModes); err != nil {
				this.ServeError(err.Error())
				return
			}
		}
	}
	rsp := struct {
		FareId    int64        `json:"fare_id"`
	    Created   time.Time    `json:"created"`
	}{FareId: v.FareId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *FareTempController) Put() {
	v := seller.FareTemplate{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.FareId, "fare_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	excludeArr := []string{"fare_id","partner_id","store_id","carry_modes"}
	updateFields, err := this.GetUpdateFields(v, "", "form", excludeArr)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	if err := seller.UpdateFareTemplateById(&v, updateFields...); err != nil{
		this.ServeError(err.Error())
		return
	}
	if len(v.CarryModesJson) > 0 {
		beego.Debug("v.CarryModesJson:", v.CarryModesJson)
		arrJson, err := helper.SplitJsonArr(v.CarryModesJson)
		if err != nil {
			this.ServeError(err.Error())
		    return
		}
        for _, str := range arrJson {
			beego.Debug("arrJson str:", str)
			var reqMode seller.CarryMode
			if err = json.Unmarshal([]byte(str), &reqMode); err != nil {
				this.ServeError(err.Error())
		        return
			}
			reqMode.Fare = &v               // pay more attention
	   	    if oldCarryMode, err := seller.GetCarryModeById(reqMode.Id); err == nil{
			    carryModeFields := []string{}
				if reqMode.CarryWay != oldCarryMode.CarryWay {
					carryModeFields = append(carryModeFields, "carry_way")
				}
				if reqMode.FirstAmount != oldCarryMode.FirstAmount {
					carryModeFields = append(carryModeFields, "first_amount")
				}
				if reqMode.FirstPiece != oldCarryMode.FirstPiece {
					carryModeFields = append(carryModeFields, "first_piece")
				}
				if reqMode.Region != oldCarryMode.Region {
					carryModeFields = append(carryModeFields, "region")
				}
				if reqMode.SecondAmount != oldCarryMode.SecondAmount {
					carryModeFields = append(carryModeFields, "second_amount")
				}
				if reqMode.SecondPiece != oldCarryMode.SecondPiece {
					carryModeFields = append(carryModeFields, "second_piece")
				}
			    if err := seller.UpdateCarryMode(&reqMode, carryModeFields...); err != nil {
		            this.ServeError(err.Error())
                    return 			
	            }
			}
	    }
	}
	fareTemplate, err := seller.GetFareTemplateById(v.FareId)
	if err != nil {
	   beego.Debug("GetFareTemplateById:", err.Error())
	   this.ServeError(err.Error())
	   return
	}
	//更新子店运费模板
	excludeSubArr := []string{"fare_id","partner_id","store_id","carry_modes","remark"}
	updateSubFields, err := this.GetUpdateFields(v, "", "form", excludeSubArr)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	remark := strconv.FormatInt(fareTemplate.FareId, 10)
	if templates, err := seller.GetFareTemplateByRemark(remark); err == nil {
		beego.Debug("templates num:", len(templates),"remark:", remark)
		for _, value := range templates {
		    v.FareId = value.FareId
			if err := seller.UpdateFareTemplateById(&v, updateSubFields...); err != nil{
				this.ServeError(err.Error())
				return
			}
			if len(v.CarryModesJson) > 0 {
				arrJson, err := helper.SplitJsonArr(v.CarryModesJson)
				if err != nil {
					this.ServeError(err.Error())
					return
				}
				for _, str := range arrJson {
					var reqMode seller.CarryMode
					if err = json.Unmarshal([]byte(str), &reqMode); err != nil {
						this.ServeError(err.Error())
						return
					}
					subCarryMode,err := seller.GetCarryModeByFareIdAndFId(value.FareId,reqMode.Id)
					if err != nil {
					    continue
						return
					}
					reqMode.Fare = value               // pay more attention
					reqMode.Id = subCarryMode.Id
					if oldCarryMode, err := seller.GetCarryModeById(reqMode.Id); err == nil{
						carryModeFields := []string{}
						if reqMode.CarryWay != oldCarryMode.CarryWay {
							carryModeFields = append(carryModeFields, "carry_way")
						}
						if reqMode.FirstAmount != oldCarryMode.FirstAmount {
							carryModeFields = append(carryModeFields, "first_amount")
						}
						if reqMode.FirstPiece != oldCarryMode.FirstPiece {
							carryModeFields = append(carryModeFields, "first_piece")
						}
						if reqMode.Region != oldCarryMode.Region {
							carryModeFields = append(carryModeFields, "region")
						}
						if reqMode.SecondAmount != oldCarryMode.SecondAmount {
							carryModeFields = append(carryModeFields, "second_amount")
						}
						if reqMode.SecondPiece != oldCarryMode.SecondPiece {
							carryModeFields = append(carryModeFields, "second_piece")
						}
						if err := seller.UpdateCarryMode(&reqMode, carryModeFields...); err != nil {
							this.ServeError(err.Error())
							return 			
						}
					}
				}
			}
		}
	}
	rsp := struct {
		    FareId int64       `json:"fare_id"`
	        Modified     time.Time   `json:"modified"`
	    }{FareId:v.FareId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *FareTempController) Delete() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
    //curUserId := this.Ctx.Input.GetData("curUserId").(int)
	v := struct {
		PartnerId int64    `form:"-"  valid:"Required"`
	    FareId    int64  `form:"fare_id" valid:"Required"`
		Id        int64  `form:"id"`
	}{PartnerId: partnerId} 
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	//如果被商品使用,禁止删除
	if exist := sale.CheckItemExistByFareId(v.FareId); exist {
	    this.ServeError("fare is used by item")
		return
	}
	if v.Id > 0 {
	    if err := seller.DeleteCarryMode(v.Id); err != nil {   
	        this.ServeError(err.Error())
		    return
	    }
	}else{
	    if err := seller.DeleteFareTemplate(v.FareId); err != nil {
			this.ServeError(err.Error())
			return
	    }
	}
	rsp := struct {
		FareId     int64       `json:"fare_id"`
		Modified   time.Time   `json:"modified"`
	}{FareId:v.FareId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
